package com.zking.web.websocketdemo.utils;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.sun.deploy.net.URLEncoder;
import org.apache.poi.ss.usermodel.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class ExcelEasyPoiUtils {
    /**
     * 导出设置隔行背景色
     * @param params
     * @param list
     * @param pojoClass
     * @param fileName
     * @param response
     */
    public static void exportExcel(ExportParams params, List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response) throws IOException {
        Workbook workbook = ExcelExportUtil.exportExcel(params,pojoClass,list);
        if (workbook != null);
        setRowBackground(workbook);
        downLoadExcel(fileName, response, workbook);
    }

    /**
     * 偶数行设置背景色
     */
    private static void setRowBackground(Workbook workbook){
        Sheet sheet = workbook.getSheetAt(0);
        CellStyle styles = ExcelStyleUtil.getStyles(workbook,false,(short) 12);
        for(int i = 0; i <= sheet.getLastRowNum(); i ++) {
            Row row = sheet.getRow(i);
            if (i%2==0 && i>0){//标题用全局的标题样式，就不单独设置样式了，所以排除标题
                for(int j = 0; j < row.getPhysicalNumberOfCells(); j ++) {
                    Cell cell = row.getCell(j);
                    cell.setCellStyle(styles);
                }
            }
        }
    }

    /**
     * 下载
     * @param fileName 文件名称
     * @param response
     * @param workbook excel数据
     */
    public static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws IOException {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + "." + "xlsx", "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }

}
